﻿using FAMailUtils;
using FAMailUtils.Data.DAO;
using FAMailUtils.Data.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OnlineBusinesses.Areas.CustomerAdmin
{
    public partial class Account : System.Web.UI.Page
    {
        AccountDAO dao = new AccountDAO();
        DepartmentDAO dao2 = new DepartmentDAO();
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    int id = 0;
                    int.TryParse(Request.QueryString["id"], out id);

                    ddlDepartment.DataSource = dao2.GetAll(((AdminCustomer_Master)Page.Master).getUserLogin().Client.UserID);
                    ddlDepartment.DataTextField = "DepartmentName";
                    ddlDepartment.DataValueField = "DepartmentID";
                    ddlDepartment.DataBind();

                    ClientDAO cdao = new ClientDAO();
                    ClientDTO company = cdao.GetByClientID(((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID);
                    lblDomain.Text = "@"+company.CompanyDomain;
                    if (id > 0)
                    {
                        AccountDTO account = dao.GetByAccountID(id, ((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID);
                        if (account.AccountID > 0)
                        {
                            AccountDTO a = dao.GetByAccountID(id, ((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID);
                            txtAccountName.Text = a.AccountName;
                            txtPhone.Text = a.Phone;
                            txtPassword.Text = a.Password;
                            txtFunction.Text = a.Function;
                            txtDomainName.Text = a.Email.Split('@')[0];
                            txtDomainName.ReadOnly = true;
                            txtAddress.Text = a.Address;
                            btnCreate.Visible = false;
                            ddlDepartment.SelectedValue = a.DepartmentID.ToString();
                            hdAccountID.Value = a.AccountID.ToString();
                        }
                    }
                    else
                    {
                        btnEdit.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Common.logs(Request.RawUrl + "-" + Common.GetCurrentMethod(), ex, Common.logType.error);
            }
        }
        public static string GetMd5Hash(string input)
        {
            MD5 md5Hash = MD5.Create();
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
        protected void btnCreate_Click(object sender, CommandEventArgs e)
        {
            try
            {
                bool isValid = true;
                if (String.IsNullOrWhiteSpace(txtAccountName.Text))
                {
                    lbNotice.Text = "Tên tài khoản không được để trống.";
                    isValid = false;
                }
                else if (String.IsNullOrWhiteSpace(txtPassword.Text))
                {
                    lbNotice.Text = "Mật khẩu không được để trống.";
                    isValid = false;
                }
                else if (txtPassword.Text != txtConfirmPassword.Text)
                {
                    lbNotice.Text = "2 mật khẩu không trùng khớp.";
                    isValid = false;
                }
                else if (String.IsNullOrWhiteSpace(lblDomain.Text))
                {
                    lbNotice.Text = "Chưa cài đặt tên domain.";
                    isValid = false;
                }

                if (isValid == true)
                {
                    FAMailUtils.Data.DTO.UserLoginDTO user = ((AdminCustomer_Master)Page.Master).getUserLogin();
                    ClientDAO cdao = new ClientDAO();
                    ClientDTO company = cdao.GetByClientID(((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID);
                    AccountDTO a = new AccountDTO();
                    a.AccountName = txtAccountName.Text;
                    a.CreateDate = DateTime.Now;
                    a.ClientID = user.Client.ClientID;
                    a.IsBlock = false;
                    a.IsMainDepartment = false;
                    a.DepartmentID = int.Parse(ddlDepartment.SelectedValue);
                    a.Phone = txtPhone.Text;
                    a.Password = GetMd5Hash(txtPassword.Text);
                    a.Function = txtFunction.Text;
                    a.Email = txtDomainName.Text + "@" + company.CompanyDomain;
                    a.Address = txtAddress.Text;
                    a.UserID = user.Client.UserID;
                    a.AccountID = dao.Create(a);
                    Response.Redirect("AccountList.aspx");
                }
            }
            catch (Exception ex)
            {
                Common.logs(Request.RawUrl + "-" + Common.GetCurrentMethod(), ex, Common.logType.error);
            }
        }

        protected void btnEdit_Click(object sender, CommandEventArgs e)
        {
            try
            {
                bool isValid = true;
                if (String.IsNullOrWhiteSpace(txtAccountName.Text))
                {
                    lbNotice.Text = "Tên tài khoản không được để trống.";
                    isValid = false;
                }
                //else if (String.IsNullOrWhiteSpace(txtPassword.Text))
                //{
                //    lbNotice.Text = "Mật khẩu không được để trống.";
                //    isValid = false;
                //}
                else if ((!String.IsNullOrWhiteSpace(txtPassword.Text) || !String.IsNullOrWhiteSpace(txtConfirmPassword.Text)) && txtPassword.Text != txtConfirmPassword.Text)
                {
                    lbNotice.Text = "2 mật khẩu không trùng khớp.";
                    isValid = false;
                }

                if (isValid == true)
                {
                    AccountDTO a = dao.GetByAccountID(Convert.ToInt32(hdAccountID.Value), ((AdminCustomer_Master)Page.Master).getUserLogin().Client.ClientID);
                    a.AccountName = txtAccountName.Text;
                    a.Phone = txtPhone.Text;
                    a.DepartmentID = int.Parse(ddlDepartment.SelectedValue);
                    a.Password = GetMd5Hash(txtPassword.Text);
                    a.Function = txtFunction.Text;
                    a.Email = txtDomainName.Text + lblDomain.Text;
                    a.Address = txtAddress.Text;

                    dao.Update(a);
                    Response.Redirect(Request.RawUrl);
                }
            }
            catch (Exception ex)
            {
                Common.logs(Request.RawUrl + "-" + Common.GetCurrentMethod(), ex, Common.logType.error);
            }
        }
    }
}